from urllib.parse import urlencode

import requests
from django.contrib.auth.hashers import make_password
from rest_framework.views import APIView
from rest_framework.response import Response

from oauth.models import OauthUser
# from workorder.settings import WEIBO_APP_ID, WEIBO_SECRET_KEY
from keke.settings import WEIBO_APP_ID, WEIBO_SECRET_KEY

from user.models import User
from utils.MyBaseView import create_token



class WeiBoURl(APIView):
    """
    获取微博二维码的url
    """

    def post(self, request):
        url = 'https://api.weibo.com/oauth2/authorize?'# 微博授权的地址
        # 携带的参数配置
        data = {
            'client_id': WEIBO_APP_ID,
            'redirect_uri': 'http://127.0.0.1:8080/oauth/callback/',
        }
        weibo_url = url + urlencode(
            data)  # https://api.weibo.com/oauth2/authorize?client_id=1584596336&redirect_uri=http%3A%2F%2F127.0.0.1%3A8888%2Foauth%2Fcallback%2F&response_type=code
        print(weibo_url)
        return Response({'code': '0', 'msg': '成功', 'data': {'url': weibo_url}})



class WeiBoCallback(APIView):
    '''
    发送微博返回的code，进行身份验证
    '''

    def post(self, request):
        code = request.data.get("code")
        data = {
            'client_id': WEIBO_APP_ID,
            'client_secret': WEIBO_SECRET_KEY,
            'grant_type': 'authorization_code',
            'code': code['code'],
            'redirect_uri': 'http://127.0.0.1:8080/oauth/callback/',
        }

        url = "https://api.weibo.com/oauth2/access_token"

        # 需要用一个http请求去请求微博准备的信息-----requests
        json_weibo_data = requests.post(url=url, data=data).json()

        # 提取其中有用的信息UID
        uid = json_weibo_data.get("uid")
        print(uid)
        # 判断是否获取到UID
        if uid:
            try:
                uid_user = OauthUser.objects.get(uid=uid)
                res_data = {
                    'code': 0,
                    "msg": "授权成功",
                    "data": {
                        "type": "0",
                        "uid": uid,
                        "username": uid_user.user.username,
                        "token": create_token(uid_user.user)
                    }
                }
                print(res_data)
                return Response(res_data)
            except Exception as e:
                res_data = {
                    'code': 0,
                    "msg": "授权成功",
                    "data": {
                        "type": "1",
                        "uid": uid,

                    }
                }
                print(res_data)
                return Response(res_data)
        else:
            return Response({"code": 999, "msg": "获取微博信息失败"})



class WeiBoBindUser(APIView):
    """
    绑定三方登录用户
    """

    def post(self, request):
        oauth_type = 1
        username = request.data.get("username")
        password = request.data.get("password")
        weibo_uid = request.data.get("weibo_uid")
        print(username,password,weibo_uid)

        if not all([username, password, weibo_uid]):
            return Response({"code": 4005, "msg": "参数不全"})

        # 判断username是否存在
        try:
            user = User.objects.get(username=username)
            oauthinfo = OauthUser.objects.create(uid=weibo_uid, oauth_type=oauth_type,
                                                 user=user)

            data = {
                "id": user.id,
                "a": None,
                "username": username,
                "email": user.email,
                "token": create_token(user),
                "type": 0
            }

            res_data = {
                "code": 0,
                "msg": "登陆成功",
                "data": data
            }
            return Response(res_data)

        except Exception as e:
            password = make_password(password)
            user = User.objects.create(username=username, password=password)
            oauthinfo = OauthUser.objects.create(uid=weibo_uid, oauth_type=oauth_type,
                                                 user=user)

            data = {
                "id": user.id,
                "role": None,
                "username": username,
                "email": user.email,
                "token": create_token(user),
                "type": 0
            }

            res_data = {
                "code": 0,
                "msg": "登陆成功",
                "data": data
            }
            return Response(res_data)


